const UserApi = require('../../../api/user.js');
const regExpUtil = require('../../utils/regExp.js');

Page({
  data: {
    formModel: {
      oldPassword: null,
      loginPassword: null,
      confirmPassword: null,
    }
  },

  onLoad(options) {},
  onReady() {},
  onShow() {},
  onHide() {},
  handleInput(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'oldPassword') {
      this.setData({['formModel.oldPassword']: value})
    } else if (target == 'loginPassword') {
      this.setData({['formModel.loginPassword']: value})
    } else if (target == 'confirmPassword') {
      this.setData({['formModel.confirmPassword']: value})
    }
  },
  formSubmit(e){
    if (!this.data.formModel.oldPassword) {
      wx.showToast({icon: 'none', title: '请输入原密码'});
    } else if (!this.data.formModel.loginPassword) {
      wx.showToast({icon: 'none', title: '请输入密码'});
    } else if (this.data.formModel.loginPassword && !regExpUtil.isLegalPsw(this.data.formModel.loginPassword)) {
      wx.showToast({icon: 'none', title: '密码必须包含6-16位字母数字'});
    } else if (!this.data.formModel.confirmPassword) {
      wx.showToast({icon: 'none', title: '请输入确认密码'});
    } else if (this.data.formModel.loginPassword != this.data.formModel.confirmPassword) {
      wx.showToast({icon: 'none', title: '两次输入密码不一致'});
    } else {
      UserApi.modifyPassword({...this.data.formModel}).then(res=>{
        if (res.retCode == '000000' && res.errCode == '000000') {
          wx.showToast({icon:'success', title: res.errMsg})
          this.setData({
            ['formModel.oldPassword']: null,
            ['formModel.loginPassword']: null,
            ['formModel.confirmPassword']: null,
          })
          setTimeout(()=>{
            wx.removeStorageSync('token')
            wx.removeStorageSync('userInfo')
            wx.removeStorageSync('userService')
            wx.redirectTo({
              url: '/packageA/pages/login/index?redirect_uri=/pages/index/index&redirect_uri_type=tab',
            })
          }, 2000)
        } else {
          if (res.errCode == '999901') {
            wx.removeStorageSync('userInfo')
            setTimeout(()=>{
              wx.redirectTo({
                url: '/packageA/pages/login/index?redirect_uri=/pages/index/index&redirect_uri_type=tab',
              })
            }, 2000)
          }
          wx.showToast({icon: 'error', title: res.errMsg})
        }
      })
    }
  },
  onUnload() {},
})